<template>
	<view class="view-content">
		<navBar title="巡检报告"></navBar>
			<view class="main-box">
				<u-form labelPosition="left" :model="form" :rules="rules" ref="form" labelWidth="auto">
					<!-- 报告类型 -->
					<u-form-item label="报告类型" borderBottom labelWidth="200rpx" prop="name" required
						@click="typeShow=true">
						<u--input v-model="form.name" disabled disabledColor="#ffffff" border="none">
						</u--input>
						<u-icon slot="right" name="arrow-right" color="#A7AEBD" size="20"></u-icon>
					</u-form-item>
					<!-- 巡查日期 -->
					<u-form-item label="巡查日期" borderBottom labelWidth="200rpx" prop="reportDate" required
						@click="inspectionDateShow=true">
						<u--input v-model="form.reportDate" disabled disabledColor="#ffffff" border="none">
						</u--input>
						<u-datetime-picker @cancel="inspectionDateShow=false" @confirm="inspectionDateConfirm"
							:show="inspectionDateShow" v-model="reportDate" mode="date"></u-datetime-picker>
						<u-icon slot="right" name="arrow-right" color="#A7AEBD" size="20"></u-icon>
					</u-form-item>
					<u-form-item label="上传巡查报告" prop="images" required>
						<u-upload :fileList="fileList1" name="1" @afterRead="afterRead" @delete="deletePic" multiple
							:maxCount="10" :previewFullImage="true" accept="image"></u-upload>
					</u-form-item>
					<compressionImage></compressionImage>
				</u-form>
			</view>
		<u-picker :show="typeShow" keyName="name" :columns="reportTypeList" v-model="type" @cancel="typeShow=false"
			@confirm="typeConfirm"></u-picker>
		<view class="footer-button">
			<view class="button-placeholder"></view>
			<view class="button-group">
				<button :loading="loading" @click="submit" class="button-primary">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import mixins from "@/utils/mixins.js"
	import {
		uploadFile,
	} from '@/utils/request'
	import {
		getPicture
	} from '@/api/doc.js' //获取图片
	import {
		saveReport
	} from "@/api/project/projectOrg.js"
	import {
		dailyCheckReportGetDocument,
		dailyCheckReportReport
	} from "@/api/emergency/emergencyDispatch.js"
	import navBar from "@/components/navBar/navBar.vue"
	import {
		imgFun
	} from "@/utils/common.js"
	import compressionImage from "@/components/compression-image/compression-image.vue"

	export default {
		mixins: [mixins],
		components: {
			navBar,
			compressionImage
		},
		data() {
			return {
				loading: false,
				typeShow: false,
				searchText: undefined,
				inspectionDateShow: false,
				form: {
					type: '',
					reportDate: '',
					name: ''
				},
				type: '',
				reportDate: '',
				fileList1: [],
				reportTypeList: [], //报告类型数据
				rules: {
					'name': {
						type: 'string',
						required: true,
						message: '请选择报告类型',
						trigger: ['change', 'blur']
					},
					'reportDate': {
						type: 'string',
						required: true,
						message: '请选择巡查日期',
						trigger: ['change', 'blur']
					},
					'images': {
						required: true,
						message: '请选择照片',
						trigger: ['upload']
					}
				},
			}
		},
		onLoad(option) {
			let project = option.porjectName + '-' + option.areaName + '-' + option.workName
			this.form.projectCascade = project
			this.reportTypeList = [this.$store.getters.dictMap['report_type']] //报告类型字典数据
			this.form.siteId = option.id
			this.form.reportDate = this.getDate(new Date())
			this.reportDate = new Date().getTime()
			this.form.name = this.reportTypeList[0][0].name
			this.form.type = this.reportTypeList[0][0].code
		},
		beforeDestroy() {
			this.$store.commit("setCompressionImageThis", null);
		},
		mounted() {
			this.$store.commit("setCompressionImageThis", this);
		},
		methods: {
			// 巡查日期
			inspectionDateConfirm(val) {
				this.form.reportDate = this.getDate(val.value)
				this.inspectionDateShow = false
			},
			//报告类型
			typeConfirm(val) {

				this.form.name = val.value[0].name
				this.form.type = val.value[0].code
				this.typeShow = false
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.log(event)
				for (var item in event.file) {
					// if (event.file[item].type == 'image') {
					// 	event.file[item].url = await imgFun(event.file[item])
					// 	event.file[item].thumb = await imgFun(event.file[item])
					// }
					this[`fileList${event.name}`].push({
						...event.file[item],
						status: 'success',
						message: ''
					})
				}

			},
			getDocument(fileList) {
				return new Promise((resolve, reject) => {
					let files = [...fileList]
					let imageJson = []
					let docId = ''
					dailyCheckReportGetDocument({
						siteId: this.form.siteId,
						reportDate: this.form.reportDate,
						name: this.form.name
					})
					.then(async res => {
						console.log(res, 'res')
						if(!res.success) return reject()
						if(res.result) {
							// 存在docId
							docId = res.result.docId
						}
						for (let i = 0; i < files.length; i++) {
							let docRes = await uploadFile({
								url: "rest/doc/uploadDoc",
								name: "attach",
								formData: docId ? {docId} : {} ,
								filePath: files[i].url
							})
							docRes = JSON.parse(docRes)
							if(!docRes.success) return
							if(!docId && i == 0) {
								// 如果没有docId 而且 是第一项 那么就把上传第一次的docId当作后面文件的docId
								docId = docRes.result.id
							}
						}
						getPicture({
							docId
						}).then(res => {
							console.log(res)
							if(!res.success) return
							imageJson = res.result.slice(res.result.length - files.length ,res.result.length).map(item => ({
								id: item.id,
								fileName: item.fileName,
								contentType: item.contentType,
								originalFileName: item.originalFileName
							}))
							resolve({
								imageJson,
								docId
							})
						})
						.catch(err => {
							reject(err)
						})

					})
					.catch(err => {
						reject(err)
					})
				})
			},
			//提交按钮
			async submit() {
				if(this.loading) return 
				this.loading = true
				let fileList = [...this.fileList1, ]
				if (fileList && fileList.length > 0) {
					uni.showLoading({
						title: '上传中',
						mask: true
					})
					uni.hideLoading();
					let isOwnerProjectId = uni.getStorageSync("isOwner")
					this.form.projectId = isOwnerProjectId || null
					let files = fileList.map((val, index) => {
						return {
							name: `attach${index}`,
							uri: val.url
						}
					})
					let docObj = await this.getDocument(fileList)
					console.log(docObj)
					this.form.docId = docObj.docId
					this.form.imageJson = docObj.imageJson
					this.form.client = 'app'
					const res = await dailyCheckReportReport({
						...this.form
					})
					console.log(res, '返回');
					let result = res
					if (result.success) {
						uni.showToast({
							icon: 'success',
							title: "保存成功",
							mask: true
						})
						uni.navigateBack()
					}else {
						this.loading = false
					}

				} else {
					this.$message("请上传图片")
					this.loading = false
				}
			}
		},
	}
</script>

<style lang="scss" scoped>
	.view-content {
		/* #ifdef MP-WEIXIN */
			padding-top: 200rpx;
		/* #endif */
	}
	.main-box {
		padding: 0 50rpx;
	}

	.outerbtn {
		height: 100rpx;
		position: fixed;
		bottom: 0px;
		width: 100%;
		right: 0px;
		.button {
			height: 92rpx;
			line-height: 92rpx;
			background: #2F80ED;
			color: #FFFFFF;
			text-align: center;
			font-size: 32rpx;
			position: fixed;
			bottom: 0;

		}
	}
</style>